<template>
  <a-modal
    :title="title || '管理物料'"
    :width="1200"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :footer="null"
    @ok="handleSubmit"
    @cancel="handleCancel">
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">

            <a-col :md="8" :sm="24" v-if="false">
              <a-form-item label="订单ID">
                <a-input v-model="queryParam.orderId" placeholder="请输入订单ID"/>
              </a-form-item>
            </a-col>

            <a-col :md="!advanced && 8 || 24" :sm="24">
            <span class="table-page-search-submitButtons"
                  :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
<!--              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>-->
<!--              <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>-->
              <a-button type="primary" @click="$refs.productAddForm.add(emsOrder)" icon="plus">新增产品</a-button>
<!--              <a-button type="primary" @click="$refs.emsMaterialIndex1.show()" icon="plus">添加已有产品</a-button>-->
            </span>
            </a-col>

          </a-row>
        </a-form>
      </div>

<!--      <div class="table-operator">-->
<!--        <a-button type="primary" @click="$refs.emsMaterialIndex1.show()" icon="plus">新增</a-button>-->
<!--      </div>-->

      <s-table
        ref="table"
        size="default"
        :columns="columns"
        :data="loadData"
        :alert="true"
        :rowKey="(record) => record.code"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        :showPagination="false"
      >


        <span slot="action" slot-scope="text, record">
        <a @click="$refs.editForm.edit(record)">编辑</a>
        <a-divider type="vertical"/>
        <a-dropdown>
          <a class="ant-dropdown-link"> 更多 <a-icon type="down"/></a>
          <a-menu slot="overlay">
            <a-menu-item>
              <a-popconfirm placement="topRight" title="确认删除？" @confirm="() => del(record)">
                <a>删除</a>
              </a-popconfirm>
            </a-menu-item>
          </a-menu>
        </a-dropdown>
      </span>
      </s-table>

<!--      <add-form ref="addForm" @ok="handleOk"/>-->
      <edit-form ref="editForm" @ok="handleOk"/>
      <ems-material-index1 ref="emsMaterialIndex1" :on-row-selected="onEmsMaterialIndex1Selected"/>
      <product-add-form ref="productAddForm" @ok="handleOk"/>

    </a-card>
  </a-modal>
</template>

<script>
import {STable} from '@/components'
import {page, del, add} from '@/api/modular/main/emsordermaterial/emsOrderMaterialManage'
// import {page, del} from '@/api/modular/main/emsorder/emsOrderManage'

// import addForm from '@/views/main/emsordermaterial/emsOrderMaterialAddForm'
import editForm from '@/views/main/emsordermaterial/emsOrderMaterialEditForm'

import materialForm from '@/views/main/emsmaterial/emsMaterialIndex'
import emsMaterialIndex1 from '@/views/main/emsmaterial/emsMaterialIndex1'

import productAddForm from '@/views/main/emsorder/emsOrderProductAddForm'
import productEditForm from '@/views/main/emsorder/emsOrderProductEditForm'

import Vue from 'vue'
import {ACCESS_TOKEN} from '@/store/mutation-types'

export default {
  components: {
    STable,
    // addForm,
    editForm,
    materialForm,
    emsMaterialIndex1,
    productAddForm,
    productEditForm,
  },

  data() {
    return {
      title: null,
      advanced: false, // 高级搜索 展开/关闭
      queryParam: {},  // 查询参数
      columns: [       // 表头
        // {
        //   title: '主键',
        //   dataIndex: 'orderMaterialId'
        // },
        // {
        //   title: '订单_ID',
        //   dataIndex: 'orderId'
        // },
        // {
        //   title: 'BOM_ID',
        //   dataIndex: 'bomId'
        // },
        // {
        //   title: '物料ID',
        //   dataIndex: 'materialId'
        // },
        {
          title: '物料名称',
          dataIndex: 'materialName'
        },
        {
          title: '物料编码',
          dataIndex: 'materialCode'
        },
        {
          title: '物料图片',
          dataIndex: 'image',
          customRender: (text, record, index) => this.$util.createFcImage(this.$createElement, text)
        },
        {
          title: '需求数',
          dataIndex: 'number'
        },
        // {
        //   title: '完成数',
        //   dataIndex: 'completedNumber'
        // },
        // {
        //   title: '进度状态',
        //   dataIndex: 'executeStatus'
        // },
        // {
        //   title: '生产进度',
        //   dataIndex: 'executeProgress'
        // },
        // {
        //   title: '附件',
        //   dataIndex: 'file'
        // },
        {
          title: '备注',
          dataIndex: 'remark'
        },
        // {
        //   title: '状态（字典 0正常 1冻结 2删除）',
        //   dataIndex: 'status'
        // },
        // {
        //   title: '创建时间',
        //   dataIndex: 'createTime'
        // },
        // {
        //   title: '创建人',
        //   dataIndex: 'createUser'
        // },
        // {
        //   title: '更新时间',
        //   dataIndex: 'updateTime'
        // },
        // {
        //   title: '更新人',
        //   dataIndex: 'updateUser'
        // },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          scopedSlots: {customRender: 'action'}
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return page(Object.assign(parameter, this.queryParam)).then((res) => {
          return res.data
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
      defaultExpandedKeys: [],
      replaceFields: {
        key: 'id',
      },
      visible: false,
      confirmLoading: false,
      emsOrder: null
    }
  },
  watch: {
    emsOrder() {
      let _this = this
      setTimeout(function () {
        _this.$refs.table.refresh()
      }, 100)
    }
  },
  computed: {
    token() {
      return Vue.ls.get(ACCESS_TOKEN)
    }
  },
  methods: {
    show(record, title) {
      this.visible = true
      this.emsOrder = record
      this.title = title
      this.queryParam.orderId = record.orderId
      this.queryParam.materialType = record.materialType
      this.queryParam.pageSize = -1
    },
    del(record) {
      del(record).then((res) => {
        if (res.success) {
          this.$message.success('删除成功')
          this.$refs.table.refresh()
        } else {
          this.$message.error('删除失败：' + res.message)
        }
      }).catch((err) => {
        this.$message.error('删除错误：' + err.message)
      })
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    handleOk() {
      this.$refs.table.refresh()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    handleSubmit() {
    },
    handleCancel() {
      this.visible = false
    },
    onEmsMaterialIndex1Selected(materialRow) {
      // console.log(`选择了原料:id=${materialRow.materialId}, code=${materialRow.materialCode}, name=${materialRow.materialName}`)
      // debugger
      let {materialId, materialName, materialCode, materialType, costPrice} = materialRow
      // 需要调用接口往订单中添加物料
      let _emsOrder = Object.assign({}, this.emsOrder)
      _emsOrder.orderMaterials = []
      let orderMaterial = {
        orderMaterialId: '',
        orderId: _emsOrder.orderId,
        bomId: '0',  // 单独选择原料时没有BOMID
        materialId: materialId,
        number: 1,
        completedNumber: 0,
        executeStatus: '0',
        executeProgress: '0',
        status: '0',
        createTime: '',
        createUser: '',
        updateTime: '',
        updateUser: '',
      }
      _emsOrder.orderMaterials.push(orderMaterial)
      add(orderMaterial).then(res => {
        if (res.success) {
          this.$message.success('新增成功')
          // this.handleCancel()
          // this.$emit('ok', values)
          this.$refs.table.refresh()
        } else {
          this.$message.info('新增失败：' + res.message)
        }
      })
      // 然后刷新table控件
    },
    imageURLFormat(text) {
      return `${this.$store.state.baseUrl}/sysFileInfo/preview?id=${text}&token=${this.token}`
    }
  }
}
</script>

<style lang="less">
.table-operator {
  margin-bottom: 18px;
}

button {
  margin-right: 8px;
}
</style>
